package tr.edu.yildiz.ce.dap.acm.util;

import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import tr.edu.yildiz.ce.dap.acm.gen.Cache;

public class CacheXmlConverter {
    
    private static Unmarshaller unMarshaller = getUnmarshaller();
    private static Marshaller marshaller = getMarshaller();

    
    private static Unmarshaller getUnmarshaller(){
        try {
            return getContext().createUnmarshaller();
        } catch (JAXBException e) {
            return null;
        }
    }
    
    private static Marshaller getMarshaller(){
        try {
            return getContext().createMarshaller();
        } catch (JAXBException e) {
            return null;
        }
    }
    
    private static JAXBContext getContext() throws JAXBException{
        return JAXBContext.newInstance(Cache.class);
    }
    
    public static String convertToXML(Object obj) throws JAXBException{
        StringWriter siteString = new StringWriter();
        Marshaller marshaller = getContext().createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(obj,siteString);
        return siteString.toString();
    }
    
    
    public static Cache convertToObject(String xmlString) throws JAXBException{
    	StringReader reader = new StringReader(xmlString);
        return (Cache) unMarshaller.unmarshal(reader);
    }
    

	public static Cache convertToObject(File file) throws JAXBException{
		return  (Cache)unMarshaller.unmarshal(file);
	}
	
	public static Cache convertToObject(InputStream inputStream) throws JAXBException{
		return (Cache)unMarshaller.unmarshal(inputStream);
	}
    
}
